package com.getpebble.android.onboarding.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Analytics.MobileAppOnboarding;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.LockerApp;
import com.getpebble.android.jsbridge.JsBridgeUtil;
import com.getpebble.android.jsbridge.JsBridgeWebClient;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants.StoreType;
import com.getpebble.android.onboarding.activity.OnboardingActivity;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.webview.WebViewUtil;
import java.util.ArrayList;
import org.json.JSONObject;

public class GrabAppsFragment extends PblBaseFragment {
    public static final String TAG = GrabAppsFragment.class.getSimpleName();
    private ArrayList<LockerApp> mAppsToLoad = new ArrayList();
    private Button mContinueButton;
    private ArrayList<String> mUuidsToUnload = new ArrayList();
    private WebView mWebView;

    private class GrabAppsWebViewClient extends JsBridgeWebClient {
        private GrabAppsWebViewClient() {
        }

        protected void handleJSBridgeMethods(String methodName, JSONObject methodArgs) {
            if (methodName.equals("setNavBarTitle")) {
                GrabAppsFragment.this.handleSetNavBarTitleRequest(methodArgs);
            } else if (methodName.equals("loadAppToDeviceAndLocker")) {
                GrabAppsFragment.this.handleLoadAppToDeviceAndLocker(methodArgs);
            } else {
                Trace.warning(TAG, "Got unhandled JsBridge method: " + methodName);
            }
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_grab_apps;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mWebView = (WebView) container.findViewById(R.id.webView);
        this.mWebView.getSettings().setDomStorageEnabled(true);
        String url = AppStoreConstants.getStoreUrl(StoreType.GET_SOME_APPS, null);
        Trace.debug(TAG, "Loading url: " + url);
        loadWebView(url);
        this.mContinueButton = (Button) container.findViewById(R.id.onboarding_continue_btn);
        this.mContinueButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                MobileAppOnboarding.logOnboardingGrabSomeAppsNextPressed();
                Activity activity = GrabAppsFragment.this.getActivity();
                if (activity != null && (activity instanceof OnboardingActivity)) {
                    OnboardingActivity onboardingActivity = (OnboardingActivity) activity;
                    if (!HttpUtils.hasInternetConnection(activity.getApplicationContext())) {
                        onboardingActivity.switchToNoConnectivityFragment();
                    } else if (GrabAppsFragment.this.mAppsToLoad.size() == 0 && GrabAppsFragment.this.mUuidsToUnload.size() == 0) {
                        GrabAppsFragment.this.goToAppInstallComplete(onboardingActivity);
                    } else {
                        GrabAppsFragment.this.goToAppInstallFragment(onboardingActivity);
                    }
                }
            }
        });
    }

    private void goToAppInstallFragment(OnboardingActivity onboardingActivity) {
        Bundle args = new Bundle();
        args.putParcelableArrayList("extra_load_app_list", this.mAppsToLoad);
        args.putStringArrayList("extra_unload_uuid_list", this.mUuidsToUnload);
        Fragment nextFragment = new AppInstallFragment();
        nextFragment.setArguments(args);
        onboardingActivity.switchScreenFragment(nextFragment);
    }

    private void goToAppInstallComplete(OnboardingActivity onboardingActivity) {
        Fragment nextFragment = new AppInstallCompleteFragment();
        Bundle args = new Bundle();
        args.putInt("extra_num_apps_installed", 0);
        args.putInt("extra_num_apps_install_failed", 0);
        nextFragment.setArguments(args);
        onboardingActivity.switchScreenFragment(nextFragment);
    }

    public void onResume() {
        super.onResume();
        handleArguments();
    }

    public void handleArguments() {
        Bundle args = getArguments();
        if (args != null && args.containsKey("extra_load_app_list")) {
            this.mAppsToLoad = args.getParcelableArrayList("extra_load_app_list");
        }
        if (args != null && args.containsKey("extra_unload_uuid_list")) {
            this.mUuidsToUnload = args.getStringArrayList("extra_unload_uuid_list");
        }
    }

    private void loadWebView(String url) {
        WebSettings webSettings = this.mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(2);
        this.mWebView.setWebViewClient(new GrabAppsWebViewClient());
        this.mWebView.setLayerType(1, null);
        WebViewUtil.appendPebbleUserAgentStringToWebview(this.mWebView);
        this.mWebView.setBackgroundColor(getResources().getColor(R.color.white));
        this.mWebView.loadUrl(url);
    }

    private void handleSetNavBarTitleRequest(JSONObject methodArgs) {
        String title = JsBridgeUtil.getTitle(methodArgs);
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
    }

    private void handleLoadAppToDeviceAndLocker(JSONObject methodArgs) {
        Trace.debug(TAG, "MethodArgs: " + methodArgs);
        LockerApp lockerApp = JsBridgeUtil.getWatchAppFromMethodArgs(methodArgs);
        if (lockerApp == null) {
            Trace.error(TAG, "Unable to add to locker; bad data.");
            JsBridgeUtil.appendResultToDataArgs(methodArgs, "added_to_locker", Boolean.valueOf(false));
            JsBridgeUtil.notifyLoadResult(this.mWebView, false, methodArgs);
            return;
        }
        MobileAppBehavior.logAddToLockerAndInstallFromWebviewRequested(lockerApp);
        addAppToLocker(lockerApp);
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "application_id", lockerApp.getId());
        JsBridgeUtil.appendResultToDataArgs(methodArgs, "added_to_locker", Boolean.valueOf(true));
        JsBridgeUtil.notifyLoadResult(this.mWebView, true, methodArgs);
        this.mAppsToLoad.add(lockerApp);
    }

    private void addAppToLocker(LockerApp lockerApp) {
        ContentValues contentValues = lockerApp.toContentValues();
        Activity activity = getActivity();
        if (activity != null) {
            contentValues.put("_needs_add", Integer.valueOf(1));
            activity.getContentResolver().insert(PblContentProviderUtil.getTableUri("locker_apps"), contentValues);
            PebbleApplication.getSyncManager().syncLockerApps();
        }
    }
}
